// Time Tracker by Eric Nadeau (nado18@gmail.com)
// Copyright (C) 2007 by Eric Nadeau
// Distributed under the terms of the GNU General Public License (see GPL.txt)

package model;

/**
 * @author Eric Nadeau (nado18@gmail.com), on Apr 21, 2004
 */
public class Project implements Comparable<Project> {
	private static final long NOT_RUNNING = -1;
	
	private String name;
	private double initial;
	private double rate;
	private long elapsed;
	
	private long activationTime;
	
	public Project() {
		name = "";
		initial = 0;
		rate = 0;
		elapsed = 0;
		activationTime = NOT_RUNNING;
	}
	
	public synchronized void start() {
		if( ! isActive() ) {
			activationTime = System.currentTimeMillis();
		}
		else {
			assert false: "You shouldn't call start() on an already active project.";
		}
	}
	
	public synchronized void stop() {
		if( isActive() ) {
			elapsed = getElapsed();
			activationTime = NOT_RUNNING;
		}
		else {
			assert false: "Don't call stop() on inactive projects.";
		}
	}
	
	public String saveString() {
		return getElapsed() + "|" + getInitial() + "|" + getRate() + "|" + getName();
	}
	
	public static Project loadString(String l) {
		int i;
		Project p = new Project();

		i = l.indexOf('|');
		p.setElapsed( Long.parseLong(l.substring(0, i)) );
		l = l.substring(i+1);

		i = l.indexOf('|');
		p.setInitial( Double.parseDouble(l.substring(0, i)) );
		l = l.substring(i+1);
		
		i = l.indexOf('|');
		p.setRate( Double.parseDouble(l.substring(0, i)) );
		l = l.substring(i+1);
		
		p.setName(l);
		
		return p;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String aName) {
		name = aName;
	}
	
	public double getInitial() {
		return initial;
	}
	
	public void setInitial(double anInitial) {
		initial = anInitial;
	}
	
	public double getRate() {
		return rate;
	}
	
	public void setRate(double aRate) {
		rate = aRate;
	}
	
	public long getElapsed() {
		if( isActive() ) {
			long now = System.currentTimeMillis();
			long then = activationTime;
			long extra = Math.round((now - then) / 1000.0);
			return elapsed + extra;
		}
		else {
			return elapsed;
		}
	}
	
	public void setElapsed(long anElapsed) {
		elapsed = anElapsed;
	}
	
	public String getBillTime() {
		return TimeConverter.longToString( getElapsed() );
	}
	
	public String getBillPrice() {
		double price = getRate() * (getElapsed()/(60.0*60)) + getInitial();
		price = Math.round(price*100) / 100.0;
		
		return price + ((price * 100 % 10 == 0) ? "0" : "");
	}
	
	public String toString() {
		return getName();
	}
	
	public boolean isActive() {
		return activationTime != NOT_RUNNING;
	}

	/* (non-Javadoc)
	 * @see java.lang.Comparable#compareTo(java.lang.Object)
	 */
	public int compareTo(Project p) {
		String name1 = getName();
		String name2 = p.getName();
		
		if( (name1==null) && (name2==null) ) {
			return 0;
		}
		else if( name1==null ) {
			return -1;
		}
		else if( name2 == null ) {
			return 1;
		}
		else {
			return name1.compareToIgnoreCase(name2);
		}
	}
}
